<script setup>
// // import { GetListComeAPI } from '@/api/statistics/procure/orderTack.js'
import { GetCustomSelsctAPI } from '$/common/index'

// 列表数据
const tableData = ref([])

// 按钮
const buttonList = ref([{ type: 'export', hasPermi: 'finance:dataChange:export' }])

// 列表枚举
const column = ref([
  { label: '客户编码', prop: 'clientCode', width: '180' },
  { label: '客户名称', prop: 'clientName', width: '180' },
  { label: '客户类别', prop: 'typeName' },
  { label: '期初余额', prop: 'balanceAmount' },
  { label: '销售金额', prop: 'amount' },
  { label: '应收金额', prop: 'closedAmount' },
  { label: '整单折扣', prop: 'packageDiscount' },
  { label: '实际收款金额', prop: 'collectionAmount' },
  { label: '应收款余额', prop: 'balanceOfAccounts' }
])

// 状态
const state = reactive({
  treeLoading: false,
  loading: false, // 列表加载状态
  btnLoading: false, // 按钮加载状态
  isShow: false, // 弹窗状态
  title: '新增', // 弹窗标题
  total: 0 // 列表总量
})

//查询表单
const ruleForm = reactive({
  time: '', //时间
  clientCode: '' //客户
})

const typeName = ref([])

// 查询条件
const query = reactive({
  pageNum: 1,
  pageSize: 10
})
const defauleTime = ref([new Date(), new Date(Date.now() + 1000 * 60 * 60 * 24)])

const SupplierType = ref([]) //客户类别下拉
// 查询条件 枚举
const selectList = ref([
  { label: '开单时间', type: '日期范围' },

  {
    label: '客户',
    model: 'materialCode',
    type: '输入框'
  },
  {
    label: '客户类别',
    model: 'materialName',
    type: '下拉单选'
  }
])

// 导出
const exportFun = () => {}

// 查询条件
const selectSubmit = val => {
  Object.keys(val).forEach(keyItem => (query[keyItem] = val[keyItem]))
  getList()
}

//查询
const submit = () => {
  getList()
}

//重置
const reset = async () => {
  ruleForm.typeName = '' //给客户下拉赋默认值
  query.typeName = ''
  ruleForm.clientCode = ''
  defaultDate() //重置为当月时间
  getList() //调取列表接口
}

//设置默认日期
const defaultDate = () => {
  //获取新的时间
  let date = new Date()
  //获取当前时间的年份转为字符串
  let year = date.getFullYear().toString()
  //获取月份，由于月份从0开始，此处要加1，判断是否小于10，如果是在字符串前面拼接'0'
  let month = date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1).toString() : (date.getMonth() + 1).toString()
  //获取天，判断是否小于10，如果是在字符串前面拼接'0'
  let da = date.getDate() < 10 ? '0' + date.getDate().toString() : date.getDate().toString()
  //字符串拼接，开始时间，结束时间
  let end = year + '-' + month + '-' + da //当天
  let beg = year + '-' + month + '-01' //当月第一天
  ruleForm.time = [beg, end] //将值设置给插件绑定的数据
}
defaultDate()

// 获取客户下拉数据
const getCustomSelsct = async () => {
  const { data: res } = await GetCustomSelsctAPI()
  SupplierType.value = res
  // ruleForm.typeName = res[0].value //给客户下拉赋默认值
  // typeName.value = res[0].value
}
getCustomSelsct()

//下拉选择
const OptChange = val => {
  query.typeName = val
}

// 获取列表
const getList = async () => {
  query.beginTime = ruleForm.time[0] //默认时间
  query.endTime = ruleForm.time[1] //默认时间
  query.clientCode = ruleForm.clientCode
  query.type = '1'
  state.loading = true
  try {
    const result = await GetListComeAPI(query)
    tableData.value = result
    // state.total = result.total
  } catch {
  } finally {
    state.loading = false
  }
}
getList()
const summaryMethod = param => {
  const { columns, data } = param
  const sums = []
  columns.forEach((column, index) => {
    if (index === 0) {
      sums[index] = '合计'
      return
    }

    const values = data.map(item => {
      // 掺入数组对比
      if (
        ['amount', 'closedAmount', 'packageDiscount', 'collectionAmount', 'balanceOfAccounts'].includes(column.property)
      ) {
        return Number(item[column.property])
      } else {
        return '-?-'
      }
    })
    // 应付款
    if (index === 9) {
      console.log(values)
      sums[index] = values[values.length] || '--'
      return
    }
    if (!values.every(value => value == '-?-')) {
      sums[index] = values.reduce((prev, curr) => {
        const value = Number(curr)
        if (!Number.isNaN(value)) {
          const number = Number(prev) + Number(curr)
          return number.toFixed(2)
        } else {
          return prev
        }
      }, 0)
    } else {
      sums[index] = '/'
    }
  })

  return sums
}

// watch(
//   () => typeName.value,
//   val => {
//     query.typeName = val
//     getList()
//   },
//   { deep: true }
// )
</script>

<template>
  <div class="app-container">
    <!-- 查询条件组件 -->
    <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" inline scroll-to-error label-width="100px">
      <el-form-item label="开单日期">
        <el-date-picker
          v-model="ruleForm.time"
          type="daterange"
          range-separator="-"
          start-placeholder="开始"
          end-placeholder="结束"
          format="YYYY-MM-DD"
          value-format="YYYY-MM-DD"
          :default-time="defauleTime"
        />
      </el-form-item>
      <el-form-item label="客户">
        <el-input v-model="ruleForm.clientCode" placeholder="请输入客户" />
      </el-form-item>
      <el-form-item label="客户类别">
        <el-select v-model="ruleForm.typeName" placeholder="请选择客户" @change="OptChange">
          <el-option v-for="item in SupplierType" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
        <!-- <p-select isValue :option="customerSel" v-model="ruleForm.clientCode" @change="OptChange" /> -->
      </el-form-item>
      <el-form-item label="">
        <el-button type="primary" @click="submit">查询</el-button>
        <el-button @click="reset">重置</el-button>
      </el-form-item>
    </el-form>
    <!-- <p-select-form :selectForm="selectList" @selectSubmit="selectSubmit" /> -->
    <el-card>
      <!-- 按钮组件 -->
      <p-button :list="buttonList" @add="addDic" />
      <!-- 表格数据 -->
      <p-table
        class="tableClass"
        summary
        summaryMethodYes
        :summaryMethod="summaryMethod"
        :isSel="false"
        :loading="state.loading"
        :data="tableData"
        :column="column"
        v-model:page="query.pageNum"
        v-model:limit="query.pageSize"
        :total="state.total"
        @change="handleSelectionChange"
        @pagination="getList"
      >
        <template #columnCell="{ column, record }">
          <!-- 辅助属性 -->
          <p-producer :data="record.auxiliaryAttribute" v-if="column.label == '辅助属性'" />
        </template>
      </p-table>
    </el-card>
  </div>
</template>
<style scoped lang="scss">
.app-container ::v-deep .el-form-item__content {
  width: 240px !important;
}
.app-container ::v-deep .el-date-editor {
  width: 240px !important;
}
</style>
